//
// Created by Andrea Petreti on 27/10/2021.
//

#ifndef ANDROIDPDFVIEWER_PDFIUM_INTERNAL_H
#define ANDROIDPDFVIEWER_PDFIUM_INTERNAL_H

extern "C" {
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <cstring>
#include <cstdio>
}

#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <android/bitmap.h>

#include <fpdfview.h>
#include <fpdf_doc.h>
#include <string>
#include <vector>
#include <mutex>
#include <exception>
#include "android-log.h"
#include "DocumentFile.h"


struct rgb {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
};

template<class string_type>
inline typename string_type::value_type *WriteInto(string_type *str, size_t length_with_null) {
    str->reserve(length_with_null);
    str->resize(length_with_null - 1);
    return &((*str)[0]);
}

inline long getFileSize(int fd) {
    struct stat file_state;

    if (fstat(fd, &file_state) >= 0) {
        return (long) (file_state.st_size);
    } else {
        LOGE("Error getting file size");
        return 0;
    }
}

char *getErrorDescription(const long error);

int jniThrowException(JNIEnv *env, const char *className, const char *message);

int jniThrowExceptionFmt(JNIEnv *env, const char *className, const char *fmt, ...);

jobject NewLong(JNIEnv *env, jlong value);

jobject NewInteger(JNIEnv *env, jint value);

uint16_t rgbTo565(rgb *color);

void rgbBitmapTo565(void *source, int sourceStride, void *dest, AndroidBitmapInfo *info);

extern "C" { //For JNI support

int getBlock(void *param, unsigned long position, unsigned char *outBuffer,
             unsigned long size);

jlong loadPageInternal(JNIEnv *env, DocumentFile *doc, int pageIndex);

void closePageInternal(jlong pagePtr);

void renderPageInternal(FPDF_PAGE page,
                        ANativeWindow_Buffer *windowBuffer,
                        int startX, int startY,
                        int canvasHorSize, int canvasVerSize,
                        int drawSizeHor, int drawSizeVer,
                        bool renderAnnot);

}
#endif //ANDROIDPDFVIEWER_PDFIUM_INTERNAL_H
